package sku

import (
	"context"
	"mall/common/excption"
	constans "mall/services/product/rpc/consts"
	"mall/services/product/rpc/internal/domain/bo"
	"mall/services/product/rpc/internal/mapper"
	"mall/services/product/rpc/internal/svc"
	"mall/services/product/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManageLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSkuManageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManageLogic {
	return &ManageLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ManageLogic) SkuManage(in *pb.SkuManageDTO) (*pb.EmptyObj, error) {
	// 1.check request dto
	skuMapper, checkErr := l.checkRequestDTO(in)
	if checkErr != nil {
		return nil, checkErr
	}
	// 2.update spu db
	saveErr := skuMapper.SkuManageForSkuIdCtx(l.ctx, l.svcCtx.DBEngin, in.SkuIdArr, in.Status)
	if saveErr != nil {
		return nil, saveErr
	}
	// 3.return obj
	return &pb.EmptyObj{}, nil
}

func (l *ManageLogic) checkRequestDTO(in *pb.SkuManageDTO) (*mapper.SkuMapper, error) {
	skuMapper := mapper.NewSkuMapper()
	skuBO := bo.SkuBO{SkuIdArr: in.SkuIdArr}
	skuBO.NeStatus = constans.SpuTakeDown
	selectCountCtx, err := skuMapper.SelectCountCtx(l.ctx, l.svcCtx.DBEngin, skuBO)
	if err != nil {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	if int(selectCountCtx) != len(in.SkuIdArr) {
		return nil, excption.NewErrCode(constans.SpuInfoNoExistError)
	}
	return skuMapper, nil
}
